import Toast from 'tdesign-miniprogram/toast/index'

const app = getApp()

Page({
  onShow() {
    wx.reportAnalytics('enter_publish_programmatically', {})
    this.getTabBar().setData({active: 'publish'})
  },
  toast(option) {
    Toast({
      context: this,
      selector: '#t-toast',
      ...option,
    });
  },
  onShareAppMessage() {
    return {
      title: '发布瞬间',
      path: '/page/publish/index'
    }
  },
  onShareTimeline() {
    '发布'
  },

  data: {
    medias: [],
    images: [],
    mediaLimit: 9,
    title: '',
    content: '',
    theme: 'light',
    visibleRange: 1,
    labels: [],
    labelChecked: {},
    label: '',
    visibleRanges: {
      1: '公开',
      2: '私密',
    },
    visible: {
      label: false,
    },
    loading: {
      submit: false,
      label: false,
    },
    user: null,
    onGlobalUserChange: null,
  },
  resetData() {
    this.setData({
      medias: [],
      images: [],
      title: '',
      content: '',
      visibleRange: 1,
      labels: [],
      labelChecked: {},
      label: '',
    })
  },
  chooseMedia() {
    wx.chooseMedia({
      count: this.data.mediaLimit - this.data.medias.length,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: (res) => {
        this.setData({
          medias: [...this.data.medias, ...res.tempFiles],
          images: [...this.data.images, ...res.tempFiles.map(i => i.tempFilePath)]
        })
      }
    })
  },
  previewImage(e) {
    const index = e.target.dataset.index
    wx.navigateTo({
      url: '/packagePublish/pages/preview/index',
      events: {
        del: (index) => {
          this.data.medias.splice(index, 1)
          this.data.images.splice(index, 1)
          this.setData({
            medias: [...this.data.medias],
            images: [...this.data.images],
          })
         },
      },
      success: (res) => {
        res.eventChannel.emit('init', { images: this.data.images, index })
      },
    })
  },
  go2visibleRange() {
    wx.navigateTo({
      url: '/packagePublish/pages/visible-range/index',
      events: {
        change: (visibleRange) => {
          this.setData({
            visibleRange
          })
         },
      },
      success: (res) => {
        res.eventChannel.emit('init', { value: this.data.visibleRange })
      },
    })
  },
  submit() {
    
    const { images, user, title, labels, content, visibleRange, loading } = this.data
    this.setData({
      loading: {
        ...loading,
        submit: true,
      }
    })
    const uploads = images.map(i => wx.cloud.uploadFile({
      cloudPath: `${user.openid}${i.substr(i.lastIndexOf('/'))}`,
      filePath: i
    }))
    Promise.all(uploads)
    .then(res => {
      const fileIds = res.map(i => i.fileID)
      return wx.cloud.callFunction({
        name: 'post',
        data: {
          action: 'insert',
          data: {
            title,
            labels,
            content,
            visibleRange,
            medias: fileIds,
            user: {
              _id: user._id,
              labels: user.labels,
              openid: user.openid,
              nickName: user.nickName,
              avatarUrl: user.avatarUrl,
            }
          }
        },
      })
    })
    .then(res =>{
      const { code, data } = res.result
      if (!code) {
        app.globalData.user = user
        data.updatedTime = new Date().toISOString()
        this.resetData()
      } else {
        this.toast({
          message: '发布失败，请稍后重试',
        });
      }
    })
    .catch(e => {
      console.error('publish error: ' + e);
      this.toast({
        message: '发布失败，请稍后重试',
      })
    })
    .finally(() => {
      this.setData({
        loading: {
          ...loading,
          submit: false,
        }
      })
    })
  },
  onContentChange(e) {
    this.setData({
      content: e.detail.value?.substr(0, 499)
    })
  },
  addLabel() {
    const { user, label, labels, labelChecked } = this.data
    if (!label) return
    labelChecked[label] = true
    if (!user.labels.includes(label)) {
      user.labels.push(label)
    }
    if (!labels.includes(label)) {
      labels.push(label)
    }
    this.setData({
      labels: [...labels],
      user: {...user},
      labelChecked: {...labelChecked}
    })
  },
  labelChange(e) {
    const { detail: {checked}, target: { dataset: { value } }} = e
    const { labels, labelChecked } = this.data
      labelChecked[value] = checked
    if (checked) {
      labels.push(value)
    } else if (labels.indexOf(value) > -1) {
      labels.splice(labels.indexOf(value), 1)
    }
    this.setData({
      labels: [...labels],
      labelChecked: {...labelChecked}
    })
  },
  labelClose(e) {
    const { target: { dataset: { value, index } }} = e
    const { user, labels, labelChecked } = this.data
    labelChecked[value] = false
    user.labels.splice(index, 1)
    const idx = labels.indexOf(value)
    if (idx > -1) {
      labels.splice(idx, 1)
    }
    this.setData({
      labels: [...labels],
      user: {...user},
      labelChecked: {...labelChecked}
    })
  },
  getUserInfoOnSubmit(e) {
    app.registerUser(e.detail.userInfo)
    .then((user) => {
      this.data.user = user
      this.submit()
    })
  },
  getUserInfoOnLabel(e) {
    app.registerUser(e.detail.userInfo)
    .then(() => this.showLabelPopup())
  },
  showLabelPopup() {
    this.labelVisibleChange({ detail: {visible: true}})
  },
  labelVisibleChange(e) {
    this.setData({
      visible: {
        ...this.data.visible,
        label: e.detail.visible,
      }
    })
  },
  onGlobalUserChange(user) {
    this.setData({ user })
  },
  onLoad() {
    this.setData({
      theme: wx.getSystemInfoSync().theme || 'light',
      user: app.globalData.user
    })
    this.data.onGlobalUserChange = this.onGlobalUserChange.bind(this)
    app.watch('user', this.data.onGlobalUserChange)
    if (wx.onThemeChange) {
      wx.onThemeChange(({theme}) => {
        this.setData({theme})
      })
    }
  },
  onUnload() {
    app.unWatch('user', this.data.onGlobalUserChange)
  }
})
